import {onMounted, onUnmounted, ref} from 'vue'
import {useUserStore} from '@/stores/user'

/**
 * 聊天WebSocket管理
 */
export function useChat() {
  const userStore = useUserStore()
  const ws = ref(null)
  const isConnected = ref(false)
  const reconnectAttempts = ref(0)
  const maxReconnectAttempts = 5
  const reconnectInterval = 3000
  const heartbeatTimer = ref(null)
  const heartbeatInterval = 30000

  // 消息处理回调
  const messageHandlers = ref(new Map())

  /**
   * 连接WebSocket
   */
  const connect = () => {
    // 检查用户是否已登录
    if (!userStore.userInfo?.userId) {
      console.warn('未登录，无法建立WebSocket连接')
      return
    }

    try {
      // 直接从 userStore 获取用户ID
      const userId = getUserId()
      if (!userId) {
        console.error('无法获取用户ID')
        return
      }

      // WebSocket需要直接连接到后端服务器，不能通过HTTP代理
      const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'
      // const wsHost = import.meta.env.VITE_WS_HOST || window.location.host
      let wsUrl = ''
      if(import.meta.env.VITE_APP_ENV === 'development'){
        wsUrl = `${protocol}//${import.meta.env.VITE_WS_HOST}/quora/ws/${userId}`
      } else {
        wsUrl = `${protocol}//${window.location.host}/quora/ws/${userId}`
      }
      console.log('正在连接WebSocket:', wsUrl)
      console.log('用户ID:', userId)

      ws.value = new WebSocket(wsUrl)

      ws.value.onopen = handleOpen
      ws.value.onmessage = handleMessage
      ws.value.onclose = handleClose
      ws.value.onerror = handleError

    } catch (error) {
      console.error('WebSocket连接失败:', error)
      handleReconnect()
    }
  }

  /**
   * 连接成功处理
   */
  const handleOpen = () => {
    console.log('✅ WebSocket连接成功')
    console.log('连接状态:', ws.value?.readyState)
    isConnected.value = true
    reconnectAttempts.value = 0
    startHeartbeat()
  }

  /**
   * 消息处理
   */
  const handleMessage = (event) => {
    try {
      const message = event.data

      // 尝试解析JSON消息
      const data = JSON.parse(message)
    

      // 根据消息类型分发处理
      switch (data.type) {
        case 'connection':
          console.log('连接确认:', data.message)
          break
        case 'private_message':
          handlePrivateMessage(data.data)
          break
        case 'online_status_change':
          handleOnlineStatusChange(data)
          break
        case 'pong':
          console.log('收到心跳响应: pong')
          break
        default:
          console.log('未知消息类型:', data.type)
      }

      // 触发注册的消息处理器
      messageHandlers.value.forEach((handler, type) => {
        if (data.type === type) {
          handler(data)
        }
      })

    } catch (error) {
      console.error('解析WebSocket消息失败:', error)
      console.error('原始消息:', event.data)
    }
  }

  /**
   * 处理私信消息
   */
  const handlePrivateMessage = (messageData) => {
   
  }

  /**
   * 处理在线状态变更
   */
  const handleOnlineStatusChange = (data) => {
    console.log('用户在线状态变更:', data)
    // 更新用户在线状态
  }

  /**
   * 连接关闭处理
   */
  const handleClose = (event) => {
    console.log('❌ WebSocket连接关闭')
    console.log('关闭代码:', event.code, '关闭原因:', event.reason)
    isConnected.value = false
    stopHeartbeat()
    handleReconnect()
  }

  /**
   * 连接错误处理
   */
  const handleError = (error) => {
    console.error('WebSocket连接错误:', error)
    isConnected.value = false
  }

  /**
   * 重连处理
   */
  const handleReconnect = () => {
    if (reconnectAttempts.value < maxReconnectAttempts) {
      reconnectAttempts.value++
      console.log(`尝试重连 (${reconnectAttempts.value}/${maxReconnectAttempts})`)
      setTimeout(connect, reconnectInterval)
    } else {
      console.error('WebSocket重连失败，已达到最大重试次数')
    }
  }

  /**
   * 开始心跳
   */
  const startHeartbeat = () => {
    heartbeatTimer.value = setInterval(() => {
      if (isConnected.value && ws.value?.readyState === WebSocket.OPEN) {
        ws.value.send('ping')
      }
    }, heartbeatInterval)
  }

  /**
   * 停止心跳
   */
  const stopHeartbeat = () => {
    if (heartbeatTimer.value) {
      clearInterval(heartbeatTimer.value)
      heartbeatTimer.value = null
    }
  }

  /**
   * 发送消息
   */
  const sendMessage = (message) => {
    if (isConnected.value && ws.value?.readyState === WebSocket.OPEN) {
      ws.value.send(JSON.stringify(message))
      return true
    } else {
      console.warn('WebSocket未连接，无法发送消息')
      return false
    }
  }

  /**
   * 注册消息处理器
   */
  const onMessage = (type, handler) => {
    messageHandlers.value.set(type, handler)
  }

  /**
   * 移除消息处理器
   */
  const offMessage = (type) => {
    messageHandlers.value.delete(type)
  }

  /**
   * 断开连接
   */
  const disconnect = () => {
    stopHeartbeat()
    if (ws.value) {
      ws.value.close()
      ws.value = null
    }
    isConnected.value = false
  }

  /**
   * 获取用户ID
   */
  const getUserId = () => {
    try {
      // 直接从 userStore 获取用户ID
      if (userStore.userInfo?.userId) {
        return userStore.userInfo.userId
      }

      return null
    } catch (error) {
      console.error('获取用户ID失败:', error)
      return null
    }
  }

  // 组件挂载时自动连接
  onMounted(() => {
    connect()
  })

  // 组件卸载时断开连接
  onUnmounted(() => {
    disconnect()
  })

  return {
    isConnected,
    connect,
    disconnect,
    sendMessage,
    onMessage,
    offMessage
  }
}
